﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using DiagramDesigner.Common.Controls;

namespace Behavior.Link
{
    public class AnchorPointAdorner : Adorner
    {
        private readonly Point[] _points;
        private readonly VisualCollection _visuals;
        private readonly List<AnchorPointThumb> _thumbs;

        public AnchorPointAdorner(UIElement adornedElement, Point[] points)
            : base(adornedElement)
        {
            _visuals = new VisualCollection(this);
            _thumbs = new List<AnchorPointThumb>();
            _points = points;
            BuildThumbs();
        }

        private void BuildThumbs()
        {
            for (int i = 0; i < _points.Length; i++)
            {
                AnchorPointThumb thumb = new AnchorPointThumb();
                thumb.Width = thumb.Height = 8;
                thumb.BorderBrush = Brushes.Black;
                thumb.BorderThickness = new Thickness(1);
                thumb.Background = Brushes.Bisque;
                _thumbs.Add(thumb);
                _visuals.Add(_thumbs[i]);
            }
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            double adornedWidth = AdornedElement.DesiredSize.Width;
            double adornedHeight = AdornedElement.DesiredSize.Width;
            for (int i = 0; i < _points.Length; i++)
            {
                double x = _points[i].X * adornedWidth - _thumbs[i].Width / 2;
                double y = _points[i].Y * adornedHeight - _thumbs[i].Height / 2;
                _thumbs[i].Arrange(new Rect(x, y, _thumbs[i].Width, _thumbs[i].Height));
            }
            
            return finalSize;
        }

        protected override int VisualChildrenCount
        {
            get
            {
                return _visuals.Count;
            }
        }

        protected override Visual GetVisualChild(int index)
        {
            return _visuals[index];
        }
    }
}
